<template>
  <div class="category">
    <nav-bar class="category-bar">
      <template slot="center">分类</template>
    </nav-bar>
    <div class="category-content">
      <scroll class="aside-content" ref="scroll">
        <category-aside
          :categoryAsideList="categoryAsideList"
          @handleMaitKeyChange="handleMaitKeyChange"
        ></category-aside>
      </scroll>
      <scroll class="main-content" ref="scroll">
        <category-main :subCategoryList="subCategoryList"></category-main>
      </scroll>
    </div>
  </div>
</template>

<script>
import {
  getCategoryAsideData,
  getSubCatagoryMainData
} from "@/network/category";

import NavBar from "@/components/common/navbar/NavBar.vue";
import Scroll from "@/components/common/scroll/Scroll.vue";

import CategoryAside from "./childCategory/CategoryAside.vue";
import CategoryMain from "./childCategory/CategoryMain.vue";

import { imgListenerMixin } from "@/common/mixin";

export default {
  components: {
    NavBar,
    Scroll,
    CategoryAside,
    CategoryMain
  },
  data() {
    return {
      categoryAsideList: [],
      subCategoryList: []
    };
  },
  mixins: [imgListenerMixin],
  created() {
    this.getCategory();
  },
  deactivated() {
    // 取消首页事件总线的监听，与首页商品图片加载分开
    this.$bus.$off("itemImgLoad", this.imgItemListener);
  },
  methods: {
    /**
     * 网络请求相关
     */
    getCategory() {
      getCategoryAsideData()
        .then(res => {
          this.categoryAsideList = res.data.category.list;
          // 记录第一条分类的maitKey
          const subCategoryMaitKey = res.data.category.list[0].maitKey;
          // 方式一: 直接调用获取subcategory
          // this.getSubCategory(subCategoryMaitKey);
          // 方式二：返回出去,在第二个then的参数里就可以拿到这个值
          return subCategoryMaitKey;
        })
        .then(maitKey => {
          this.getSubCategory(maitKey);
        });
    },

    // 获取分类的商品
    getSubCategory(maitKey) {
      getSubCatagoryMainData(maitKey).then(res => {
        this.subCategoryList = res.data.list;
        // 点击更换分类类型后main-content重新回到顶部
        this.$refs.scroll.scrollTo(0, 0, 500);
      });
    },

    /**
     * 事件处理相关
     */
    // 点击对应的aside bar请求对应的subcategory数据
    handleMaitKeyChange(maitKey) {
      this.getSubCategory(maitKey);
    }
  }
};
</script>

<style scoped>
.category {
  height: 100vh;
  position: relative;
}

.category-bar {
  background-color: var(--color-tint);
  z-index: 9;
  color: #fff;
}

.category-content .aside-content {
  position: absolute;
  left: 0;
  right: 0;
  top: 44px;
  bottom: 49px;
  overflow: hidden;
}

.category-content .main-content {
  position: absolute;
  left: 100px;
  right: 0;
  top: 44px;
  bottom: 49px;
  width: calc(100% - 100px);
  overflow: hidden;
}
</style>
